# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: MUX_λ_scan.py
  @time: 2022/5/16 10:07
  @desc:
"""
import time

from math import *
from ATS.hardwarescan import conf_file_manager
from ATS.application.LCR_App.U2722A_App import U2722A_App
from ATS.application.LASER_App.L8164B_App import L8164B_App
from ATS.application.LASER_App.N7744C_App import N7744C_App
from ATS.application.VNA_App.N5225B_App import N5225BApp
from ATS.util.calcu_step_util import get_points_list, get_step_list
from utils.read_ini_2_dict import get_option_value, get_refrence_data
from utils.get_wave_power_util import get_wave_power_value
from ATS.util.save_data_2_csv_util import saveData2CSV
from matplotlib import pyplot as plt
from ATS.switchdriver.LightSwitchDriver import LightSwitchDriver
# from sympy import symbols, diff
import numpy as np
from utils.find3db_util import find3db_util


def Mux_λ_scan(bias_channel, bias_channel_voltage=0, bias_channel_current_range="120mA", bias_channel_limit="0.12",
               heater_channel=2, heater_channel_current_range="120mA", heater_channel_limit="0.12",
               start_wave=1250, stop_wave=1360, step_wave=0.1):
    u2722a_app = U2722A_App("SMU4")
    l8164b_app = L8164B_App("SS3")
    n7744c_app = N7744C_App("SS2")

    u2722a_app.set_voltage(bias_channel_voltage, bias_channel)
    u2722a_app.set_voltage_range(bias_channel)
    u2722a_app.set_current_range_limit(bias_channel_current_range, bias_channel_limit, bias_channel)
    u2722a_app.set_voltage_range(heater_channel)
    u2722a_app.set_current_range_limit(heater_channel_current_range, heater_channel_limit, heater_channel)
    wave_list = get_step_list(start_wave, stop_wave, step_wave)
    wavelength = l8164b_app.get_source_wavelength()
    wave_power_tuple = get_refrence_data()

    loss_gc = get_option_value()

    power_list = []
    heater_current_list = []
    for wave in wave_list:
        l8164b_app.set_wave_length(wave)
        loss_sys = get_wave_power_value(wave, wave_power_tuple)
        input_value = l8164b_app.fetch_input_power()
        output_power = n7744c_app.get_power_value()
        power = get_power(input_value,output_power,loss_sys,loss_gc)
        if power:
            power_list.append(power)
        heater_current = u2722a_app.get_current_value(heater_channel)
        if heater_current:
            heater_current_list.append(heater_current)

    u2722a_app.output_state(0,bias_channel)
    u2722a_app.output_state(0,heater_channel)


def get_power(input_value, output_value, loss_sys, loss_gc, const1=-0.2, const2=3):
    power = float(input_value) - float(output_power) - float(loss_sys) - 2 * float(loss_gc) - (-0.2) - 3
    if power:
        return power
